package yxgf.oem.oemquotemgt.mservice.service.impl;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.ebg.egf.common.annotation.Autowired;
import yxgf.oem.oemquotemgt.commons.constants.MarketNumConstant;
import yxgf.oem.oemquotemgt.commons.dto.*;
import yxgf.oem.oemquotemgt.commons.utils.YxCustomApiResult;
import yxgf.oem.oemquotemgt.mservice.service.IMarketBillService;
import yxgf.oem.oemquotemgt.mservice.service.IPriceService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @description： 营销单服务
 * @version: v1.0
 * @author: Junit
 * @date: 2025/5/17
 */
public class MarketBillServiceImpl implements IMarketBillService {
    private static final Log logger = LogFactory.getLog(MarketBillServiceImpl.class);

    @Autowired
    private IPriceService iPriceService;

    @Override
    public CustomApiResult<MarketProductDto> calProPrice(List<MarketFormulaReq> formulaList, List<MarketFormulaPriceDto> priceList, MarketBaseCostDto cost) {
        logger.info("IMarketBillService -> calProPrice");

        MarketProductDto resDto = new MarketProductDto();
        /*
         * 1、配方、友商
         */
        BigDecimal formulaMoney = BigDecimal.ZERO;
        BigDecimal comPrice = BigDecimal.ZERO;
        for (MarketFormulaReq formulaReq : formulaList) {
            BigDecimal[] moneyArr = getPricing(priceList, formulaReq.getMatId());
            // SUM(原料定价*使用量)
            if(formulaReq.getDosage() != null || formulaReq.getDosage().compareTo(BigDecimal.ZERO) != 0){
                formulaMoney = formulaMoney.add(formulaReq.getDosage().multiply(moneyArr[0]));
            }
            comPrice = comPrice.add(formulaReq.getDosage().multiply(moneyArr[1]));
        }
        resDto.setForPrice(formulaMoney);

        /*
         * 2、产品
         * 配方成本*（1+损耗百分比/100）+包装费用+其他费用+配送
         */
        BigDecimal wastagePer = cost.getWastageCost().divide(new BigDecimal(MarketNumConstant.DEF_PER),5, RoundingMode.HALF_UP);
        BigDecimal wastage = new BigDecimal(MarketNumConstant.DEF_BASE_PER).add(wastagePer);
        BigDecimal proPrice = (formulaMoney.multiply(wastage))
                .add(cost.getPackCost())
                .add(cost.getDeliCost())
                .add(cost.getOtherCost());
        resDto.setProPrice(proPrice);

        CustomApiResult<MarketProductDto> result = new CustomApiResult<>();
        result.setData(resDto);
        return result;
    }

    /**
     * 查找原料价格
     * 定价、友商价
     * @param priceList
     * @return
     */
    private BigDecimal[] getPricing(List<MarketFormulaPriceDto> priceList, Long materialId) {
        BigDecimal[] moneyArr = new BigDecimal[2];
        for (MarketFormulaPriceDto formulaReq : priceList) {
            if (materialId.equals(formulaReq.getMatId())) {
                if (formulaReq.getPricing() != null) {
                    moneyArr[0] = (formulaReq.getPricing() != null) ? formulaReq.getPricing() : BigDecimal.ZERO;
                    moneyArr[1] = (formulaReq.getComPrice() != null) ? formulaReq.getComPrice() : BigDecimal.ZERO;
                }
            }
        }
        return moneyArr;
    }

    @Override
    public List<MarketFormulaDto> calForProportion(List<MarketFormulaReq> req, BigDecimal matTotal) {
        // 获取占比
        List<MarketFormulaDto> resList = new ArrayList<>();
        if (matTotal != null && matTotal.compareTo(BigDecimal.ZERO) != 0) {
            for (MarketFormulaReq tem : req) {
                MarketFormulaDto dto = new MarketFormulaDto();
                dto.setMatId(tem.getMatId());
                dto.setDosage(tem.getDosage());
                BigDecimal propProp = BigDecimal.ZERO;
                if (tem.getDosage() != null) {
                    propProp = tem.getDosage().divide(matTotal,2, RoundingMode.HALF_UP);
                }
                dto.setProportion(propProp);
                resList.add(dto);
            }
        }
        return resList;
    }


    @Override
    public CustomApiResult<List<MarketNutItemDto>> getNutItemProportion(List<MarketFormulaReq> formulaList) {
        /**
         * 获取原料集
         */
        List<Long> matCode = new ArrayList<>();
        for (MarketFormulaReq tem : formulaList) {
            matCode.add(tem.getMatId());
        }

        /**
         * 构建多条件查询 ? NT
         */
        QFilter orgFilter = new QFilter("yxgf_material.number", QCP.equals, matCode);
        QFilter matFilter = new QFilter("yxgf_material.number", QCP.equals, matCode);
        QFilter dateFilter = new QFilter("yxgf_tallydate", QCP.equals, matCode);
        QFilter filter = orgFilter.or(matFilter).or(dateFilter);

        /**
         * 根据原料查询物料中营养占比
         * 无数据，假设查询
         * 1、原料营养项目存储在单据体中：yxgf_material_nutrition，字段为：yxgf_prop
         */
        DynamicObjectCollection nutCollection = QueryServiceHelper.query("yxgf_material_nutrition",
                "entryentity.yxgf_materielfield.number," +
                        "entryentity.yxgf_prop", new QFilter[]{filter}, "createtime");

        /**
         * 计算占比量
         */
        List<MarketNutItemPropDto> marketNutItemPropList = new ArrayList<>();
        BigDecimal total = new BigDecimal(0);
        for (DynamicObject entry : nutCollection) {
            DynamicObject matDObj = (DynamicObject) entry.get("yxgf_material_code");
            long number = (long) matDObj.get("number");
            BigDecimal ItemDosagePer = (BigDecimal) entry.get("yxgf_prop");
            BigDecimal dosage = getMatDosage(formulaList, number);

            MarketNutItemPropDto tem = new MarketNutItemPropDto();
            tem.setMatId(number);
            tem.setDosage(dosage);
            BigDecimal simDosage = dosage.multiply(ItemDosagePer);
            tem.setProportion(simDosage);
            total = total.add(simDosage);
            marketNutItemPropList.add(tem);
        }

        /**
         * 占比
         */
        List<MarketNutItemDto> nutItemList = new ArrayList<>();
        for (MarketNutItemPropDto mnp : marketNutItemPropList) {
            MarketNutItemDto tem = new MarketNutItemDto();
            tem.setItemId(mnp.getMatId());
            BigDecimal itemProp = total.divide(mnp.getProportion());
            tem.setProportion(itemProp);
            nutItemList.add(tem);
        }

        /**
         * Res
         */
        CustomApiResult<List<MarketNutItemDto>> result = new CustomApiResult<>();
        result.setData(nutItemList);
        return result;
    }

    /**
     * 获取用量
     *
     * @param formulaList
     * @param number
     * @return
     */
    private BigDecimal getMatDosage(List<MarketFormulaReq> formulaList, Long number) {
        for (int i = 0; i < formulaList.size(); i++) {
            if (formulaList.get(i).getMatId().equals(number)) {
                return formulaList.get(i).getDosage();
            }
        }
        return BigDecimal.ZERO;
    }

    @Override
    public CustomApiResult<List<MarketFormulaPriceDto>> bachCulMatPrice(String cusCode,List<MarketFormulaReq> formulaList) {
        logger.info("IMarketBillService -> bachCulMatPrice");

        List<Long> ids = new ArrayList<>();
        // 获取原料id
        for (MarketFormulaReq req : formulaList){
            ids.add(req.getMatId());
        }

        QFilter idsQFilter = new QFilter("id", QCP.in, ids);
        List<MarketFormulaPriceDto> mfpDto = new ArrayList<>();
        // 友商价
        List<MarketBatComPriceReq> req = new ArrayList<>();
        // 获取价格
        List<MarketBatComPriceDto> price = iPriceService.getBatchComPrice(cusCode,req);

        return YxCustomApiResult.success(mfpDto);
    }
}
